package com.group3.filter;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.group3.utils.JWTUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class AuthorityInterceptor implements HandlerInterceptor {
    private String authority;
    public AuthorityInterceptor(){

    }

    public AuthorityInterceptor(String auth){
        this.authority = auth;
    }

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        //获取请求头中的令牌
        String token = request.getHeader("token");

        Map<String, Object> map = new HashMap<>();
        DecodedJWT jwt = JWTUtils.getToken(token);
        //System.out.println("验证了权限");
        if(jwt.getClaim("type").asString().equals(authority)){
            return true;
        }else {
            map.put("code",403);
            map.put("data", false);
            map.put("msg", "你没有此权限");
            //响应到前台: 将map转为json
            String json = new ObjectMapper().writeValueAsString(map);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().println(json);
            return false;
        }
    }
}
